let input = document.querySelector("input");
let content = document.querySelector(".content");
let t = 0;
let todoList = [];

function init() {
  let local = localStorage.getItem("todoList");
  let tmp = local.split(",");
  let len = tmp.length / 2;

  for (let j = 0; j < len; j++) {
    todoList.push([tmp[j * 2], tmp[j * 2 + 1]]);
  }
  console.log(todoList);
  for (let j = 0; j < len; j++) {
    console.log(todoList[j][1] === "1");
    if (todoList[j][1] === "1") createTodo(todoList[j][0], 1);
    else if (todoList[j][1] === "0") createTodo(todoList[j][0], 0);
    else t++;
  }
  t = len;
}

init();

input.addEventListener("keydown", () => {
  if (event.keyCode !== 13) return;
  let info = input.value;
  todoList.push([info, 0]);
  localStorage.setItem("todoList", todoList);
  input.value = "";
  createTodo(info);
});

function createTodo(info, finished) {
  //   console.log(finished);
  let newTodo = document.createElement("div");
  let newInfo = document.createElement("span");
  let newClose = document.createElement("span");
  let i = t;
  newTodo.classList.add("todo");
  newInfo.classList.add("info");
  newClose.classList.add("iconfont");
  newClose.classList.add("icon-close");
  newClose.style.fontSize = "30px";
  newClose.style.cursor = "pointer";
  newInfo.textContent = info;
  if (finished) {
    console.log("fin");
    newInfo.classList.add("finished");
    todoList[i][1] = 1;
  }
  newTodo.appendChild(newInfo);
  newTodo.appendChild(newClose);
  content.appendChild(newTodo);
  newClose.addEventListener("click", () => {
    content.removeChild(newTodo);
    todoList[i][1] = 2;
    localStorage.setItem("todoList", todoList);
  });
  newInfo.addEventListener("click", () => {
    if (newInfo.classList.contains("finished")) {
      newInfo.classList.remove("finished");
      todoList[i][1] = 0;
    } else {
      newInfo.classList.add("finished");
      todoList[i][1] = 1;
    }
    localStorage.setItem("todoList", todoList);
  });
  t++;
}
